package com.fragments.sendmail;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.Utility.MessageManager;
import com.Utility.Utility;
import com.Utility.ValidateText;
import com.Utility.WebServiceCommunicator.WebServiceFlag;
import com.adapters.RecepientAdapter;
import com.adapters.db.GroupTableAdapter;
import com.controls.ws.ContactWSControl;
import com.controls.ws.GroupWSControl;
import com.dialogs.InforConfirmDialog;
import com.events.WebServiceCommunicatorListener;
import com.fragments.BaseFragment;
import com.objects.Contact;
import com.objects.Group;
import com.objects.Recepient;
import com.objects.ValidateTextResponse;
import com.senditcertified.mail.R;
import com.views.HorizontalListView;

public class RecepientsFragment extends BaseFragment implements
		RecepientAdapter.OnClickAction, View.OnClickListener,
		CompoundButton.OnCheckedChangeListener, WebServiceCommunicatorListener {
	private View mLayoutAddContact, mLayoutRecepients, mLayoutRecepientDetails;
	private HorizontalListView mListRecepients;
	private RecepientAdapter mRecepientAdapter;
	private EditText mEdtAddContactEmail, mEdtAddContactFirstName,
			mEdtAddContactLastName;
	private EditText mEdtRecepientFirstName, mEdtRecepientLastName,
			mEdtRecepientEmail, mEdtRecepientCountryCode,
			mEdtRecepientAccessCode;
	private CheckBox mCbSendTextAlert, mCbRestrictForwarding,
			mCbElectronicReceptance;
	private ArrayList<Contact> mContacts;
	private ArrayList<Group> mGroups = null;
	private ContactWSControl mWSContact;
	private ProgressDialog mDialog;
	private GroupWSControl mWSGroup;
	private GroupTableAdapter mTAGroup;

	public List<Recepient> getRecipients() {
		List<Recepient> recepients = new ArrayList<Recepient>();
		for (int i = 0; i < mRecepientAdapter.getCount(); i++) {
			recepients.add(mRecepientAdapter.getItem(i));
		}
		return recepients;
	}

	private InforConfirmDialog mInforConfirmDialog;

	@Override
	protected void initViews() {
		mLayoutRecepients = getView().findViewById(R.id.layout_recepient_main);
		mLayoutAddContact = getView().findViewById(R.id.layout_add_recepient);
		mLayoutRecepientDetails = getView().findViewById(
				R.id.layout_recepient_details);

		mListRecepients = (HorizontalListView) getView().findViewById(
				R.id.list_recepients);

		mEdtAddContactEmail = (EditText) getView().findViewById(
				R.id.edt_add_recepient_email);
		mEdtAddContactFirstName = (EditText) getView().findViewById(
				R.id.edt_add_recepient_firstname);
		mEdtAddContactLastName = (EditText) getView().findViewById(
				R.id.edt_add_recepient_lastname);

		mEdtRecepientFirstName = (EditText) getView().findViewById(
				R.id.edt_recepient_first_name);
		mEdtRecepientLastName = (EditText) getView().findViewById(
				R.id.edt_recepient_last_name);
		mEdtRecepientEmail = (EditText) getView().findViewById(
				R.id.edt_recepient_email);
		mEdtRecepientCountryCode = (EditText) getView().findViewById(
				R.id.edt_recepient_country_code);
		mEdtRecepientAccessCode = (EditText) getView().findViewById(
				R.id.edt_access_code);

		mCbSendTextAlert = (CheckBox) getView().findViewById(
				R.id.cb_send_text_alert);
		mCbRestrictForwarding = (CheckBox) getView().findViewById(
				R.id.cb_restrict_forwarding);
		mCbElectronicReceptance = (CheckBox) getView().findViewById(
				R.id.cb_electronic_receptance);

	}

	@Override
	protected void initComponents() {
		mDialog = new ProgressDialog(getActivity().getParent());
		mDialog.setCancelable(false);
		mDialog.setMessage(getString(R.string.loader));

		mTAGroup = new GroupTableAdapter(getActivity());
		mWSGroup = new GroupWSControl(getActivity(), this);
		mWSContact = new ContactWSControl(getActivity(), this);

		if (mRecepientAdapter == null) {
			mRecepientAdapter = new RecepientAdapter(getActivity(),
					new ArrayList<Recepient>());
			mRecepientAdapter.setAction(this);
		}
		if (mRecepientAdapter.getCount() == 0) {
			setCurrentRecepient(null);
		} else {
			setCurrentRecepient(mRecepientAdapter.getItem(mRecepientAdapter
					.getCurrentPosition()));
		}
		if (mListRecepients.getAdapter() == null)
			mListRecepients.setAdapter(mRecepientAdapter);
	}

	@Override
	protected void addListener() {
		getView().findViewById(R.id.btn_help_access_code).setOnClickListener(
				this);
		getView().findViewById(R.id.btn_help_electronic_receptance)
				.setOnClickListener(this);
		getView().findViewById(R.id.btn_help_restrict_forwarding)
				.setOnClickListener(this);
		getView().findViewById(R.id.btn_help_send_text_alert)
				.setOnClickListener(this);
		getView().findViewById(R.id.btn_select_contact)
				.setOnClickListener(this);
		getView().findViewById(R.id.btn_select_group).setOnClickListener(this);
		getView().findViewById(R.id.btn_add_contact).setOnClickListener(this);
		getView().findViewById(R.id.btn_back_to_recepient).setOnClickListener(
				this);

		mEdtRecepientAccessCode.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				try {
					mRecepientAdapter.getItem(
							mRecepientAdapter.getCurrentPosition())
							.setAccessCode(s.toString());
				} catch (Exception e) {

				}
			}
		});
		mCbElectronicReceptance.setOnCheckedChangeListener(this);
		mCbRestrictForwarding.setOnCheckedChangeListener(this);
		mCbSendTextAlert.setOnCheckedChangeListener(this);
		mLayoutRecepientDetails.setOnTouchListener(new View.OnTouchListener() {
			float downX, downY;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					downX = event.getRawX();
					downY = event.getRawY();
					return true;
				case MotionEvent.ACTION_UP:
					float deltaX = event.getRawX() - downX;
					float deltaY = event.getRawY() - downY;
					if (Math.abs(deltaX) >= 30
							&& Math.abs(deltaY) < Math.abs(deltaX)) {
						if (deltaX > 0) {
							if (mRecepientAdapter.getCurrentPosition() > 0) {

								mRecepientAdapter
										.setCurrentPosition(mRecepientAdapter
												.getCurrentPosition() - 1);
								mRecepientAdapter.notifyDataSetChanged();
								setCurrentRecepient(mRecepientAdapter
										.getItem(mRecepientAdapter
												.getCurrentPosition()));
								return true;
							}
						} else {
							if (mRecepientAdapter.getCurrentPosition() < mRecepientAdapter
									.getCount() - 1) {
								mRecepientAdapter
										.setCurrentPosition(mRecepientAdapter
												.getCurrentPosition() + 1);
								mRecepientAdapter.notifyDataSetChanged();
								setCurrentRecepient(mRecepientAdapter
										.getItem(mRecepientAdapter
												.getCurrentPosition()));
								return true;
							}
						}
					}
					break;

				default:
					break;
				}
				return false;
			}
		});
	}

	@Override
	protected int initLayout() {
		// TODO Auto-generated method stub
		return R.layout.sendmail_recipients_fragment;
	}

	@Override
	public void onItemClick(Recepient recepient, int position) {
		setCurrentRecepient(recepient);

	}

	@Override
	public void onRemoveClick(Recepient recepient, int position) {
		if (mRecepientAdapter.getCount() == 0) {
			setCurrentRecepient(null);
		} else {
			if (position > 0)
				setCurrentRecepient(mRecepientAdapter.getItem(position - 1));
		}

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_help_access_code) {
		} else if (id == R.id.btn_help_electronic_receptance) {
		} else if (id == R.id.btn_help_restrict_forwarding) {
		} else if (id == R.id.btn_help_send_text_alert) {
		} else if (id == R.id.btn_select_contact) {
			if (mContacts == null) {
				mWSContact.getContacts(Utility.getStringPreference(
						getActivity(), Utility.KEY_LOGIN_TOKEN, ""));
			} else {
				selectContacts();
			}
		} else if (id == R.id.btn_select_group) {
			if (mGroups == null) {
				mWSGroup.getGroups(Utility.getStringPreference(getActivity(),
						Utility.KEY_LOGIN_TOKEN, ""));
			} else {
				selectGroups();
			}
		} else if (id == R.id.btn_add_contact) {
			addContact();
		} else if (id == R.id.btn_back_to_recepient) {
			mLayoutAddContact.setVisibility(View.GONE);
			mLayoutRecepients.setVisibility(View.VISIBLE);
		} else {
		}
	}

	private void selectContacts() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()
				.getParent());
		String[] items = new String[mContacts.size() + 1];
		items[0] = "Add New Contact";

		for (int i = 0; i < mContacts.size(); i++) {
			items[i + 1] = mContacts.get(i).getName();
		}
		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					mLayoutAddContact.setVisibility(View.VISIBLE);
					mLayoutRecepients.setVisibility(View.GONE);
					break;

				default:
					Contact contact = mContacts.get(which - 1);
					boolean contain = false;
					for (int i = 0; i < mRecepientAdapter.getCount(); i++) {
						Contact contact2 = mRecepientAdapter.getItem(i)
								.getContact();
						if (contact.getEmailAddress().equalsIgnoreCase(
								contact2.getEmailAddress())) {
							contain = true;
							break;
						}
					}
					if (!contain) {
						Recepient recepient = new Recepient();
						recepient.setContact(contact);
						addRecepient(recepient);
					}
					break;
				}
			}
		});
		builder.create().show();
	}

	private void selectGroups() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()
				.getParent());
		String[] items = new String[mGroups.size()];

		for (int i = 0; i < mGroups.size(); i++) {
			items[i] = mGroups.get(i).getTitle();
		}
		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Group group = mGroups.get(which);
				mWSGroup.getGroupMember(
						Utility.getStringPreference(getActivity().getParent(),
								Utility.KEY_LOGIN_TOKEN, ""), group.getID());
			}
		});
		builder.create().show();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		int id = buttonView.getId();
		if (id == R.id.cb_send_text_alert) {
			mRecepientAdapter.getItem(mRecepientAdapter.getCurrentPosition())
					.setSendTextAlert(isChecked);
		} else if (id == R.id.cb_restrict_forwarding) {
			mRecepientAdapter.getItem(mRecepientAdapter.getCurrentPosition())
					.setRestrictForwarding(isChecked);
		} else if (id == R.id.cb_electronic_receptance) {
			mRecepientAdapter.getItem(mRecepientAdapter.getCurrentPosition())
					.setElectronicAcceptance(isChecked);
		} else {
		}
	}

	public void setCurrentRecepient(Recepient recepient) {
		if (recepient == null) {
			mLayoutRecepientDetails.setVisibility(View.GONE);
		} else {
			mLayoutRecepientDetails.setVisibility(View.VISIBLE);
			mEdtRecepientAccessCode.setText(recepient.getAccessCode());
			mEdtRecepientEmail
					.setText(recepient.getContact().getEmailAddress());
			mEdtRecepientFirstName.setText(recepient.getContact()
					.getFirstName());
			mEdtRecepientLastName.setText(recepient.getContact().getLastName());
			mEdtRecepientCountryCode.setText(recepient.getContact()
					.getCountryCode());

			mCbElectronicReceptance.setChecked(recepient
					.isElectronicAcceptance());
			mCbRestrictForwarding.setChecked(recepient.isRestrictForwarding());
			mCbSendTextAlert.setChecked(recepient.isSendTextAlert());
		}
	}

	public void addRecepient(Recepient recepient) {
		mRecepientAdapter.add(recepient);
		mRecepientAdapter.setCurrentPosition(mRecepientAdapter
				.getPosition(recepient));
		mRecepientAdapter.notifyDataSetChanged();
		setCurrentRecepient(recepient);
	}

	@Override
	public void onConnectionOpen(WebServiceFlag flag) {
		mDialog.show();
	}

	@Override
	public void onConnectionError(WebServiceFlag flag, String error) {
		if (mDialog.isShowing()) {
			mDialog.dismiss();
		}

	}

	@Override
	public void onConnectionDone(WebServiceFlag flag, String response) {
		if (mDialog.isShowing()) {
			mDialog.dismiss();
		}
		if (flag == WebServiceFlag.GET_CONTACT) {
			mContacts = mWSContact.parseContact(response);
			selectContacts();

		} else if (flag == WebServiceFlag.GET_GROUP) {
			mGroups = mWSGroup.parseGroups(response);
			mTAGroup.clear();
			for (int i = 0; i < mGroups.size(); i++) {
				try {
					mTAGroup.add(mGroups.get(i), i);
				} catch (Exception e) {
				}
			}
			selectGroups();

		} else if (flag == WebServiceFlag.GET_GROUP_MEMBER) {
			ArrayList<Contact> lst = mWSGroup.parseGroupMemberContact(response);
			for (Contact contact : lst) {
				boolean contain = false;
				for (int i = 0; i < mRecepientAdapter.getCount(); i++) {
					if (mRecepientAdapter.getItem(i).getContact()
							.getEmailAddress() != null
							&& mRecepientAdapter
									.getItem(i)
									.getContact()
									.getEmailAddress()
									.equalsIgnoreCase(contact.getEmailAddress())) {
						contain = true;
					}
				}
				if (!contain) {
					Recepient recepient = new Recepient();
					recepient.setContact(contact);
					addRecepient(recepient);
				}
			}
			setCurrentRecepient(mRecepientAdapter.getItem(mRecepientAdapter
					.getCurrentPosition()));

		} else if (flag == WebServiceFlag.ADD_CONTACT) {
			String returnValue = mWSContact.parseAction(response,
					"AddContact_ExtResult");
			if (returnValue != null && returnValue.length() > 0) {
				MessageManager
						.showToast(getActivity().getParent(), returnValue);
			}
			Contact contact = new Contact();
			contact.setFirstName(mEdtAddContactFirstName.getText().toString()
					.trim());
			contact.setLastName(mEdtAddContactLastName.getText().toString()
					.trim());
			contact.setEmailAddress(mEdtAddContactEmail.getText().toString()
					.trim());
			Recepient recepient = new Recepient();
			recepient.setContact(contact);
			mRecepientAdapter.add(recepient);
			mRecepientAdapter.notifyDataSetChanged();

			mLayoutAddContact.setVisibility(View.GONE);
			mLayoutRecepients.setVisibility(View.VISIBLE);
		}

	}

	public void addContact() {
		ValidateText validater = new ValidateText();
		ValidateTextResponse mCheck = validater.validateTextLength(
				mEdtAddContactFirstName, 0, 50);
		if (!mCheck.isOK()) {
			showInforConfirm("The First Name was wrong!", mCheck.getMessage());
			return;
		}
		mCheck = null;
		mCheck = validater.validateTextLength(mEdtAddContactLastName, 0, 50);
		if (!mCheck.isOK()) {
			showInforConfirm("The Last Name was wrong!", mCheck.getMessage());
			return;
		}
		mCheck = null;
		mCheck = validater.validateEmail(mEdtAddContactEmail, 100);
		if (!mCheck.isOK()) {
			showInforConfirm("Invalid Email Format!", mCheck.getMessage());
			return;
		}
		mWSContact.addContact(Utility.getStringPreference(getActivity()
				.getParent(), Utility.KEY_LOGIN_TOKEN, ""), mEdtAddContactEmail
				.getText().toString().trim(), mEdtAddContactFirstName.getText()
				.toString().trim(), mEdtAddContactLastName.getText().toString()
				.trim());
	}

	private void showInforConfirm(String title, String message) {
		if (mInforConfirmDialog != null) {
			mInforConfirmDialog.dismiss();
			mInforConfirmDialog = null;
		}
		mInforConfirmDialog = new InforConfirmDialog(getActivity().getParent());
		mInforConfirmDialog.setTitle(title);
		mInforConfirmDialog.setMessage(message);
		mInforConfirmDialog.show();
	}
}
